package kr.co.handysoft.common.server;

import java.io.IOException;
import java.net.ServerSocket;

import kr.co.handysoft.common.registry.SmartPoliceRegistry;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

public class ControlServer extends Thread {

	private ServerSocket serverSocket;
	private Document doc;
	private boolean serviceFlag = true;

	public ControlServer(Document doc) {
		this.doc = doc;
		try {
			Element listenerElement = (Element)XPath.selectSingleNode(doc, "//system/listener");
			String portString = listenerElement.getAttributeValue("port");
			System.out.println("port : " + portString);
			serverSocket = new ServerSocket(Integer.parseInt(portString));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void run() {
		super.run();
		while(this.serviceFlag){
			try {
				new ServerCommandHandler(serverSocket.accept(), doc).start();
			} catch (IOException e) {}
		}
	}

	public void close() {
		try {
			if (this.serverSocket != null) this.serverSocket.close();
			this.serviceFlag = false;
			SmartPoliceRegistry.clientRunStat = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
